<?php
/*
 * [recordsingle]
 *
 */

namespace WebApper\Shortcode;

/*
 * [recordsingle]
 *
 */
class RecordSingle extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'recordsingle';
	protected $defaults = array(
		'id' => null,					// The unique ID to use for the shortcode. Default: none. Required.
		'usercap' => 'edit_others_posts',	// The minimum user capability required to access the singleview, for other user's records (when the user is not the post author). OPTIONS: 'logged_out', 'read', 'edit_posts', 'edit_others_posts', 'edit_users', 'edit_pages', 'edit_plugins'. Default 'edit_others_posts'.
		'ownercap' => 'edit_posts',			// The minimum user capability required to access the singleview, for the user's own records (when the user is the post author). OPTIONS: 'logged_out', 'read', 'edit_posts', 'edit_others_posts', 'edit_users', 'edit_pages', 'edit_plugins'. Default 'edit_posts'.
		'fieldset' => null,					// The set of fields to include in the singleview. Default: none. Required if 'include' is not specified. You may use one or both.
		'include' => null,					// field-id's of individual fields to include in the singleview. Default: none. Required if 'fieldset' is not specified. You may use one or both.
		'exclude' => null,					// field-id's of individual fields to exclude in the singleview. Default: none.
		'titlefield' => null,				// The field to use for new rocord post titles. Default: none.
		'editor' => 'true',					// Whether to enable add, edit & delete controls to the singleview. Default: true.
		'view' => 'boxes',					// 
		'showall' => 'false',					// 
		'successsave' => 'Save successful!',			// The message to display upon successful editor save. Default: 'Save successful!'
		'failuresave' => 'Save unsuccessful.',			// The message to display upon unsuccessful editor save. Default: 'Save unsuccessful.'
		'successupdate' => 'Update successful!',		// The message to display upon successful editor update. Default: 'Update successful!'
		'failureupdate' => 'Update unsuccessful.',		// The message to display upon unsuccessful editor update. Default: 'Update unsuccessful.'
		'successdelete' => 'Deletion successful!',		// The message to display upon successful editor deletion. Default: 'Deletion successful!'
		'failuredelete' => 'Deletion unsuccessful.',	// The message to display upon unsuccessful editor deletion. Default: 'Deletion unsuccessful.'
	);

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );

		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;

        // Check if current user has proper privileges
			if ( !$this->user_has_cap( $usercap, $ownercap ) )
				return;

        // Check if a record ID was passed
			if ( empty( $_GET['postID'] ) )
				return 'Invalid record ID.';

		// Get the single post
			$postID = $_GET['postID'];  // Set the post ID
			$single_post = get_post( $postID );

		// Clear any 'task' notifications for this item
			global $current_user;
			get_currentuserinfo();
			web_apper_delete_notifications_by_item_id( $current_user->ID, 'task', $postID );

		// Get the fields
			$this->get_fields( $atts );
			/* Arrange the fields into array of fieldsets sorted by fieldset_order,
			 * with the fieldset as the item key and each item containing an
			 * array of the fieldset's fields sorted by field_order
			 */
			$fieldsets = array();
			foreach ( $this->fields as $field ) :
				if ( !array_key_exists( $field['fieldset_id'], $fieldsets ) ) :
					$fieldsets[ $field['fieldset_id'] ] = array(
						'fieldset_id' =>  $field['fieldset_id'],
						'fieldset_name' => $field['fieldset_name'],
						'fields' => array(),
					);
				endif;
				$fieldsets[ $field['fieldset_id'] ]['fields'][] = $field;
				$fieldIDs .= $field['field_id'] . ',';
			endforeach;

		// Ouput form & accordion HTML
			?>
            
            <header class="page-header">
                <form id="web_apper_form" name="web_apper_form" enctype="text/plain" class="form-inline pull-right">
                    <input type="hidden" id="action" name="action" value="web_apper<?php echo $this->shortcode; ?>">
                    <?php wp_nonce_field('WebApperAwesomeness!87','web_apper_nonce'); ?>
                    <input type="hidden" id="web_apper_task" name="web_apper_task" value="change_record_type" />
                    <input type="hidden" id="web_apper_ID" name="web_apper_id" value="<?php echo $postID; ?>" />
                    <div class="input-append">
                        <select id="record_type" name="record_type" class="input-med">
                            <option>change <?php echo $single_post->post_type; ?> to</option>
                            <?php
                            $posttypes  = get_option( 'web_apper_cpts', array() );  // Get CPTs array from site options
                            foreach ( $posttypes as $posttype_id => $posttype ) :
								if ( $single_post->post_type != $posttype_id ) :
									echo '<option value="' . $posttype_id . '">' . $posttype['name_singular'] . '</option>';
                            	endif;
							endforeach;
                            ?>
                        </select>
                        <button id="changeRecordType" type="button" class="btn">submit</button>
                    </div>
                </form>
                <h1 class="page-title"><?php echo $single_post->post_title; ?></h1>
            </header><!-- .page-header -->
            
            <div class="clearfix"></div>
            
			<div class="accordion accordion-record-single" id="accordion-<?php echo $single_post->post_type; ?>">

            <?php
            // Configure form settings
            $config['prevent'] = array('bootstrap', 'jQuery', 'focus');  // Prevents scripts from loading twice
            $config['view'] = new \PFBC\View\VerticalRecordSingle;
            $config['action'] = admin_url('admin-ajax.php');
            $config['ajax'] = 1;
            $config['ajaxCallback'] = 'parseResponse' . $id;
            // Build the form
            $form = new \PFBC\Form($id);
            $form->configure($config);
            $form->addElement(new \PFBC\Element\Hidden('web_apper_form', $id));
            $form->addElement(new \PFBC\Element\Hidden('web_apper_nonce', wp_create_nonce( 'WebApperAwesomeness!87' )));
            $form->addElement(new \PFBC\Element\Hidden('action', 'web_apper' . $this->shortcode));
            $form->addElement(new \PFBC\Element\Hidden('web_apper_task', 'update'));
            $form->addElement(new \PFBC\Element\Hidden('web_apper_fields', $fieldIDs));
            $form->addElement(new \PFBC\Element\Hidden('web_apper_success_update', $successupdate));
            $form->addElement(new \PFBC\Element\Hidden('web_apper_failure_update', $failureupdate));
            $form->addElement(new \PFBC\Element\Hidden('web_apper_id', $postID));
            ?>

			<?php
            	$fieldsetCounter = 0;
				foreach ( $fieldsets as $fieldset ) : $fieldsetCounter++;  // Loop thru array of fieldsets
			?>
    
                <?php $form->addElement(new \PFBC\Element\HTML('
                <div class="accordion-group">
                    <div class="accordion-heading">
						')); ?>
						<?php
                            $form->addElement(new \PFBC\Element\Button('Update', 'submit', array(
                                'id' => 'submit-' . $fieldset['fieldset_id'],
                                'class' => 'submit-record hide',
                                'data-loading-text' => 'Updating...'
                            )));
                        ?>
                        <?php $form->addElement(new \PFBC\Element\HTML('
                        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-record-single" href="#collapse-' . $fieldset['fieldset_id'] . '"><i class="icon-plus"></i> ' . $fieldset['fieldset_name'] . '</a>
                    </div>
                    <div id="collapse-' . $fieldset['fieldset_id'] . '" class="accordion-body collapse">
                        <div class="accordion-inner">
							<div class="accordion2col">
							')); ?>
	
								<?php
								$fieldsCount = count($fieldset['fields']);  // Get the total number of feilds
								$firstTableTRCount = ceil( ($fieldsCount / 2) );  // Set the number of table rows in the first 'div.spanX'.
								$fieldCounter = 0;  // Loop iteration counter
								foreach ( $fieldset['fields'] as $field ) : $fieldCounter++;
								?>
								
									<?php
										$field['required'] = false;
										$field['default_value'] = get_post_meta( $postID, $field['field_id'], true);
										$this->add_form_field( $field, $form );
									?>
								
								<?php if ( $fieldCounter == $firstTableTRCount ) : ?>
							
							<?php $form->addElement(new \PFBC\Element\HTML('
							</div>
							<div class="accordion2col">
							')); ?>

								<?php endif; ?>

                                <?php endforeach; ?>
							
							<?php $form->addElement(new \PFBC\Element\HTML('
							</div>
                    	</div>
                	</div>
                </div>
				')); ?>
			<?php
				endforeach;
                $form->render();  // Output the form                
            ?>

			</div>
            <script type="text/javascript">

				jQuery(document).ready(function($) {

					//Show and Hide Tab View
					$('#tab_task').click( function(e) {
						$('#tasks').css({'display':'block'});		
						$('#tags').css({'display':'none'});	
						$('#paymentReporting').css({'display':'none'});	
						$('#paymentMethods').css({'display':'none'});	
						$('#paymentTerms').css({'display':'none'});				
					});	
								  
					$('#tab_tag').click( function(e) {					
						$('#tasks').css({'display':'none'});
						$('#paymentReporting').css({'display':'none'});	
						$('#paymentMethods').css({'display':'none'});	
						$('#paymentTerms').css({'display':'none'});			
						$('#tags').css({'display':'block'});
											
					});
					
					$('#tab_payment_reporting').click( function(e) {					
						$('#paymentReporting').css({'display':'block'});
						$('#tasks').css({'display':'none'});									
						$('#tags').css({'display':'none'});
						$('#paymentMethods').css({'display':'none'});	
						$('#paymentTerms').css({'display':'none'});	
					});
					$('#tab_payment_methods').click( function(e) {					
						$('#paymentMethods').css({'display':'block'});
						$('#tasks').css({'display':'none'});									
						$('#tags').css({'display':'none'});
						$('#paymentReporting').css({'display':'none'});	
						$('#paymentTerms').css({'display':'none'});
											
					});
					$('#tab_payment_terms').click( function(e) {					
						$('#paymentTerms').css({'display':'block'});
						$('#tasks').css({'display':'none'});									
					    $('#tags').css({'display':'none'});
						$('#paymentReporting').css({'display':'none'});	
						$('#paymentMethods').css({'display':'none'});	
											
					});

					//  Show/Hide edit button on collaspe
					$('.collapse').on('show', function () {
						var nParent = $(this).parent();
						$('.submit-record' , nParent).fadeIn(400);
					});
					$('.collapse').on('hide', function () {
						var nParent = $(this).parent();
						$('.submit-record' , nParent).fadeOut(400);
					});

					// Show collaspable fieldsets
					<?php if ( $showall == 'true' ) : ?>
						$('#site-content .collapse').collapse('show');
					<?php endif; ?>

					// aJax $_POST to change post type
					$('#changeRecordType').on("click", function() {
						$('.alert').remove();  // Close any alerts that may be open
						var data = $("form#web_apper_form").serialize();
						$.post( "<?php echo site_url('wp-admin/admin-ajax.php'); ?>", data, function(response) {
								var result = $.parseJSON(response);  // Parse response
								$(".page-header").prepend(result.htmlalert);  // Show and alert
						});
					});

				});
				
				jQuery("form#<?php echo $id; ?>").bind('submit', function() {
					jQuery('.alert').alert('close');  // Close any alerts that may be open
				});
				
				function parseResponse<?php echo $id; ?>(response) {
					var result = jQuery.parseJSON(response);  // Parse response
					jQuery("form#<?php echo $id; ?>").prepend(result.htmlalert);  // Insert into Modal
				}
			</script>
            <div class="tabbable">
                <ul id="singleRecordTabs" class="nav nav-tabs">
                    <li class="active"><a href="#tasks" data-toggle="tab" id="tab_task">Tasks</a></li>
                   	<li><a href="#paymentTerms" data-toggle="tab" id="tab_payment_terms">Payment Terms</a></li>
                  	<li><a href="#paymentMethods" data-toggle="tab" id="tab_payment_methods">Payment Methods</a></li>
                  	<li><a href="#paymentReporting" data-toggle="tab" id="tab_payment_reporting">Payment Reporting</a></li>
                    <li><a href="#tags" data-toggle="tab" id="tab_tag">Email Tags</a></li>
                    <li class="hide"><a href="#add_task" data-toggle="tab">New task</a></li>
                </ul>
                <div class="tab-content" id="tasks" style="display:block;">
                    <div class="tab-pane active fade in" >
                        <?php do_shortcode("[task_box id='taskBox']"); ?>
                    </div>
                </div>
                <?php do_shortcode("[payment_terms id='paymentTerms']"); ?>
              	<?php do_shortcode("[payment_methods id='paymentMethods']"); ?>
              	<?php do_shortcode("[payment_reporting id='paymentReporting']"); ?>
                <?php do_shortcode("[record_emails id='mailBox']"); ?>
            </div> 
			
			<?php
	}

    /**
     * Checks if a shortcode has required attributes
     *
	 * @param string $usercap
     * @since 1.0
     */
	protected function has_req_attrs( $atts ) {
		// Check for required shortcode attributes
		if ( $atts['id'] == null )
			return 'You must give the shortcode a unique ID, i.e., [shortcode id=\'form-1\']';
		if ( $atts['fieldset'] == null && $atts['include'] == null )
			return 'You must specify the \'fieldset\' or \'include\' attribute so you have some fields the indextable, i.e., [indextable fieldset=\'group_1\']';
		return true;
	}

    /**
     * Handles ajax requests
     *
     * @since 1.0
     */
	public function sendAjaxResponse() {
		check_ajax_referer( 'WebApperAwesomeness!87', 'web_apper_nonce' );  // Verify the security nonce
		if ( $_POST['web_apper_task'] == 'update' ) :
			echo json_encode( $this->update_record() );
		elseif ( $_POST['web_apper_task'] == 'change_record_type' ) :
			echo json_encode( $this->change_record_type() );
		endif;
		die();  // Prevents ajax from returning a '0'
	}

    /**
     * Update a record from $_POST
     *
     * @since 1.0
     */
	public function update_record() {
		// Update post
		$postID = $_POST['web_apper_id'];
		$title = $this->setTitle();
		$postData = array(
			'ID'			=> $postID,
			'post_title'	=> trim($title),
		);
		$result = wp_update_post( $postData );
		
		// If post was updated successfully
		if ( $result  ) : 
			$this->update_custom_fields_by_id( $postID, $_POST['web_apper_fields'] );  // Save post meta
			return $this->sendResponse( $_POST['web_apper_success_save'], 'alert-success', 'Hurray!', true );  // Send Response
		else :
		// Else post not updated
			return $this->sendResponse( $_POST['web_apper_success_save'], 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Change a record post type
     *
     * @since 1.0
     */
	public function change_record_type() {
		// Set post type
		$postID = $_POST['web_apper_id'];
		$result = set_post_type( $postID, $_POST['record_type'] );

		// If post was updated successfully
		if ( $result  ) :
			return $this->sendResponse( 'Record has been changed to ' . $_POST['record_type'] . '.', 'alert-success', 'Hurray!', true );  // Send Response
		else :
		// Else post not updated
			return $this->sendResponse( 'The record type was not changed. Please try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

}

$initialize = new RecordSingle(); 

?>